"""时间工具模块

提供时间相关的工具函数。
"""

import random
from datetime import datetime, timedelta
from typing import List, Tuple


def generate_time_range(
        start_time: datetime,
        end_time: datetime,
        interval_minutes: int = 60
) -> List[datetime]:
    """生成时间范围内的时间点列表
    
    Args:
        start_time: 开始时间
        end_time: 结束时间
        interval_minutes: 时间间隔（分钟）
        
    Returns:
        时间点列表
    """
    times = []
    current_time = start_time

    while current_time <= end_time:
        times.append(current_time)
        current_time += timedelta(minutes=interval_minutes)

    return times


def generate_random_time_in_range(
        start_time: datetime,
        end_time: datetime
) -> datetime:
    """在指定时间范围内生成随机时间
    
    Args:
        start_time: 开始时间
        end_time: 结束时间
        
    Returns:
        随机时间
    """
    time_diff = end_time - start_time
    random_seconds = random.randint(0, int(time_diff.total_seconds()))
    return start_time + timedelta(seconds=random_seconds)


def format_duration(seconds: float) -> str:
    """格式化持续时间
    
    Args:
        seconds: 秒数
        
    Returns:
        格式化的时间字符串
    """
    if seconds < 1:
        return f"{seconds * 1000:.2f}ms"
    elif seconds < 60:
        return f"{seconds:.2f}s"
    elif seconds < 3600:
        minutes = int(seconds // 60)
        secs = seconds % 60
        return f"{minutes}m {secs:.2f}s"
    else:
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = seconds % 60
        return f"{hours}h {minutes}m {secs:.2f}s"


def get_time_range_for_days(days: int) -> Tuple[datetime, datetime]:
    """获取指定天数的时间范围
    
    Args:
        days: 天数
        
    Returns:
        (开始时间, 结束时间)
    """
    end_time = datetime.now()
    start_time = end_time - timedelta(days=days)
    return start_time, end_time


def get_time_range_for_hours(hours: int) -> Tuple[datetime, datetime]:
    """获取指定小时数的时间范围
    
    Args:
        hours: 小时数
        
    Returns:
        (开始时间, 结束时间)
    """
    end_time = datetime.now()
    start_time = end_time - timedelta(hours=hours)
    return start_time, end_time


def parse_datetime_string(date_str: str, format_str: str = "%Y-%m-%d %H:%M:%S") -> datetime:
    """解析日期时间字符串
    
    Args:
        date_str: 日期时间字符串
        format_str: 格式字符串
        
    Returns:
        datetime对象
    """
    return datetime.strptime(date_str, format_str)


def datetime_to_string(dt: datetime, format_str: str = "%Y-%m-%d %H:%M:%S") -> str:
    """将datetime对象转换为字符串
    
    Args:
        dt: datetime对象
        format_str: 格式字符串
        
    Returns:
        格式化的日期时间字符串
    """
    return dt.strftime(format_str)
